<template>
	<view class="login-page">
		<!-- 背景特效 -->
		<view class="bg-effects">
			<view class="gradient-bg"></view>
			<view class="particle" v-for="(item, index) in particles" :key="index" :style="item.style"></view>
		</view>
		
		<!-- 返回按钮 -->
		<view class="back-btn" @tap="goBack">
			<uni-icons type="left" size="24" color="#fff"></uni-icons>
		</view>
		
		<!-- 主要内容 -->
		<view class="content">
			<!-- Logo区域 -->
			<view class="logo-section">
				<image class="logo" src="/static/logo.png" mode="aspectFit"></image>
				<text class="app-name">抖阳记录没好生活</text>
			</view>
			
			<!-- 表单区域 -->
			<view class="form-section">
				<!-- 切换标签 -->
				<view class="tabs">
					<view class="tab" :class="{ active: isLogin }" @tap="switchToLogin">登录</view>
					<view class="tab" :class="{ active: !isLogin }" @tap="switchToRegister">注册</view>
				</view>
				
				<!-- 登录表单 -->
				<view class="form" v-if="isLogin">
					<view class="input-wrapper">
						<view class="input-group" :class="{ 'error': loginErrors.username }">
							<uni-icons type="person" size="20" color="#666"></uni-icons>
							<input 
								class="input" 
								type="text" 
								placeholder="请输入账号" 
								placeholder-style="color: #666"
								v-model="loginForm.username"
								@input="clearError('login', 'username')"
							/>
						</view>
						<view class="error-message" v-if="loginErrors.username">
							<text v-for="(error, index) in loginErrors.username" :key="index">{{ error }}</text>
						</view>
					</view>
					<view class="input-wrapper">
						<view class="input-group" :class="{ 'error': loginErrors.password }">
							<uni-icons type="locked" size="20" color="#666"></uni-icons>
							<input 
								class="input" 
								:type="showLoginPassword ? 'text' : 'password'" 
								placeholder="请输入密码" 
								placeholder-style="color: #666"
								v-model="loginForm.password"
								@input="clearError('login', 'password')"
							/>
							<view class="eye-icon" @tap="showLoginPassword = !showLoginPassword">
								<uni-icons :type="showLoginPassword ? 'eye-slash' : 'eye'" size="20" color="#666"></uni-icons>
							</view>
						</view>
						<view class="error-message" v-if="loginErrors.password">
							<text v-for="(error, index) in loginErrors.password" :key="index">{{ error }}</text>
						</view>
					</view>
					<view class="remember-me">
						<view class="checkbox-wrapper" @tap="rememberMe = !rememberMe">
							<view class="checkbox" :class="{ 'checked': rememberMe }">
								<text v-if="rememberMe" class="check-icon">✓</text>
							</view>
							<text class="checkbox-label">记住我</text>
						</view>
					</view>
					<button class="submit-btn" @tap="handleLogin">登录</button>
				</view>
				
				<!-- 注册表单 -->
				<view class="form" v-else>
					<view class="input-wrapper">
						<view class="input-group" :class="{ 'error': registerErrors.username }">
							<uni-icons type="person" size="20" color="#666"></uni-icons>
							<input 
								class="input" 
								type="text" 
								placeholder="请输入账号" 
								placeholder-style="color: #666"
								v-model="registerForm.username"
								@input="clearError('register', 'username')"
							/>
						</view>
						<view class="error-message" v-if="registerErrors.username">
							<text v-for="(error, index) in registerErrors.username" :key="index">{{ error }}</text>
						</view>
					</view>
					<view class="input-wrapper">
						<view class="input-group" :class="{ 'error': registerErrors.password }">
							<uni-icons type="locked" size="20" color="#666"></uni-icons>
							<input 
								class="input" 
								:type="showRegisterPassword ? 'text' : 'password'" 
								placeholder="请输入密码" 
								placeholder-style="color: #666"
								v-model="registerForm.password"
								@input="clearError('register', 'password')"
							/>
							<view class="eye-icon" @tap="showRegisterPassword = !showRegisterPassword">
								<uni-icons :type="showRegisterPassword ? 'eye-slash' : 'eye'" size="20" color="#666"></uni-icons>
							</view>
						</view>
						<view class="error-message" v-if="registerErrors.password">
							<text v-for="(error, index) in registerErrors.password" :key="index">{{ error }}</text>
						</view>
					</view>
					<view class="input-wrapper">
						<view class="input-group" :class="{ 'error': registerErrors.confirmPassword }">
							<uni-icons type="locked" size="20" color="#666"></uni-icons>
							<input 
								class="input" 
								:type="showConfirmPassword ? 'text' : 'password'" 
								placeholder="请确认密码" 
								placeholder-style="color: #666"
								v-model="registerForm.confirmPassword"
								@input="clearError('register', 'confirmPassword')"
							/>
							<view class="eye-icon" @tap="showConfirmPassword = !showConfirmPassword">
								<uni-icons :type="showConfirmPassword ? 'eye-slash' : 'eye'" size="20" color="#666"></uni-icons>
							</view>
						</view>
						<view class="error-message" v-if="registerErrors.confirmPassword">
							<text v-for="(error, index) in registerErrors.confirmPassword" :key="index">{{ error }}</text>
						</view>
					</view>
					<button class="submit-btn" @tap="handleRegister">注册</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { login, register } from '@/api/auth.js'

const isLogin = ref(true)
const loginForm = ref({
	username: '',
	password: ''
})
const registerForm = ref({
	username: '',
	password: '',
	confirmPassword: ''
})

// 错误信息
const loginErrors = ref({
	username: null,
	password: null
})
const registerErrors = ref({
	username: null,
	password: null,
	confirmPassword: null
})

// 密码显示/隐藏状态
const showLoginPassword = ref(false)
const showRegisterPassword = ref(false)
const showConfirmPassword = ref(false)

// 记住我
const rememberMe = ref(false)

// 清除错误信息
function clearError(formType, field) {
	if (formType === 'login') {
		loginErrors.value[field] = null
	} else {
		registerErrors.value[field] = null
	}
}

// 处理校验错误
function handleValidationErrors(errors, formType) {
	if (formType === 'login') {
		loginErrors.value = {
			username: null,
			password: null
		}
		errors.forEach(error => {
			if (error.field === 'username') {
				loginErrors.value.username = error.errors
			} else if (error.field === 'password') {
				loginErrors.value.password = error.errors
			}
		})
	} else {
		registerErrors.value = {
			username: null,
			password: null,
			confirmPassword: null
		}
		errors.forEach(error => {
			if (error.field === 'username') {
				registerErrors.value.username = error.errors
			} else if (error.field === 'password') {
				registerErrors.value.password = error.errors
			} else if (error.field === 'confirmPassword') {
				registerErrors.value.confirmPassword = error.errors
			}
		})
	}
}

// 粒子特效
const particles = ref([])
let animationTimer = null

// 生成粒子
function generateParticles() {
	const count = 50
	particles.value = []
	for (let i = 0; i < count; i++) {
		particles.value.push({
			style: {
				left: Math.random() * 100 + '%',
				top: Math.random() * 100 + '%',
				width: Math.random() * 4 + 2 + 'px',
				height: Math.random() * 4 + 2 + 'px',
				animationDelay: Math.random() * 3 + 's',
				animationDuration: Math.random() * 3 + 2 + 's'
			}
		})
	}
}

// 动画粒子
function animateParticles() {
	animationTimer = setInterval(() => {
		particles.value.forEach(particle => {
			const left = parseFloat(particle.style.left)
			const top = parseFloat(particle.style.top)
			particle.style.left = (left + (Math.random() - 0.5) * 2) + '%'
			particle.style.top = (top + (Math.random() - 0.5) * 2) + '%'
		})
	}, 100)
}

function switchToLogin() {
	isLogin.value = true
	// 清除注册表单的错误
	registerErrors.value = {
		username: null,
		password: null,
		confirmPassword: null
	}
	// 重置密码显示状态
	showRegisterPassword.value = false
	showConfirmPassword.value = false
}

function switchToRegister() {
	isLogin.value = false
	// 清除登录表单的错误
	loginErrors.value = {
		username: null,
		password: null
	}
	// 重置密码显示状态
	showLoginPassword.value = false
}

async function handleLogin() {
	// 清除之前的错误
	loginErrors.value = {
		username: null,
		password: null
	}
	
	if (!loginForm.value.username) {
		loginErrors.value.username = ['请输入账号']
		return
	}
	if (!loginForm.value.password) {
		loginErrors.value.password = ['请输入密码']
		return
	}
	
	try {
		// 调用登录API
		const res = await login(loginForm.value.username, loginForm.value.password)
		
		// 从data中获取token（data可能是字符串或对象）
		let token = null
		let userInfo = null
		console.log("11111",res);
		if (res.data) {
			// 如果data是字符串，尝试解析为JSON
			if (typeof res.data === 'string') {
				try {
					const parsedData = JSON.parse(res.data)
					token = parsedData.token
					userInfo = parsedData.userInfo
				} catch (e) {
					// 如果解析失败，可能是token直接是字符串
					token = res.data
				}
			} else if (typeof res.data === 'object') {
				// 如果data是对象，直接获取
				token = res.data.token
				userInfo = res.data.userInfo
			}
		}
		
		// 保存token
		if (token) {
			uni.setStorageSync('token', token)
		}
		
		// 保存用户信息
		if (userInfo) {
			uni.setStorageSync('userInfo', userInfo)
		}
		
		// 如果勾选了记住我，保存账号密码
		if (rememberMe.value) {
			uni.setStorageSync('rememberedUsername', loginForm.value.username)
			uni.setStorageSync('rememberedPassword', loginForm.value.password)
			uni.setStorageSync('rememberMe', true)
		} else {
			// 如果没有勾选，清除之前保存的账号密码
			uni.removeStorageSync('rememberedUsername')
			uni.removeStorageSync('rememberedPassword')
			uni.removeStorageSync('rememberMe')
		}
		
		uni.showToast({ title: '登录成功', icon: 'success' })
		setTimeout(() => {
			// 跳转到首页
			uni.reLaunch({
				url: '/pages/index/index'
			})
		}, 1500)
	} catch (error) {
		// 处理参数校验错误
		if (error.validationErrors && Array.isArray(error.validationErrors)) {
			handleValidationErrors(error.validationErrors, 'login')
		} else {
			console.error('登录失败:', error)
		}
	}
}

async function handleRegister() {
	// 清除之前的错误
	registerErrors.value = {
		username: null,
		password: null,
		confirmPassword: null
	}
	
	if (!registerForm.value.username) {
		registerErrors.value.username = ['请输入账号']
		return
	}
	if (!registerForm.value.password) {
		registerErrors.value.password = ['请输入密码']
		return
	}
	if (registerForm.value.password !== registerForm.value.confirmPassword) {
		registerErrors.value.confirmPassword = ['两次密码不一致']
		return
	}
	
	try {
		// 调用注册API
		const res = await register(registerForm.value.username, registerForm.value.password)
		
		// 注册成功后，可以选择自动登录
		// 如果后端返回token，则保存
		if (res.data && res.data.token) {
			uni.setStorageSync('token', res.data.token)
		}
		if (res.data && res.data.userInfo) {
			uni.setStorageSync('userInfo', res.data.userInfo)
		}
		
		uni.showToast({ title: '注册成功', icon: 'success' })
		setTimeout(() => {
			// 如果注册后自动登录（有token），则跳转到首页；否则切换到登录页
			if (res.data && res.data.token) {
				uni.reLaunch({
					url: '/pages/index/index'
				})
			} else {
				isLogin.value = true
				registerForm.value = { username: '', password: '', confirmPassword: '' }
			}
		}, 1500)
	} catch (error) {
		// 处理参数校验错误
		if (error.validationErrors && Array.isArray(error.validationErrors)) {
			handleValidationErrors(error.validationErrors, 'register')
		} else {
			console.error('注册失败:', error)
		}
	}
}

function goBack() {
	uni.navigateBack()
}

// 加载记住的账号密码
function loadRememberedCredentials() {
	const remembered = uni.getStorageSync('rememberMe')
	if (remembered) {
		const username = uni.getStorageSync('rememberedUsername')
		const password = uni.getStorageSync('rememberedPassword')
		if (username) {
			loginForm.value.username = username
			rememberMe.value = true
		}
		if (password) {
			loginForm.value.password = password
		}
	}
}

onMounted(() => {
	generateParticles()
	animateParticles()
	// 加载记住的账号密码
	loadRememberedCredentials()
})

onUnmounted(() => {
	if (animationTimer) {
		clearInterval(animationTimer)
	}
})
</script>

<style lang="scss" scoped>
.login-page {
	width: 100vw;
	height: 100vh;
	background: #000;
	position: relative;
	overflow: hidden;
}

// 背景特效
.bg-effects {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	overflow: hidden;
	z-index: 0;
}

.gradient-bg {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: radial-gradient(ellipse at top, rgba(102, 126, 234, 0.15) 0%, transparent 50%),
				radial-gradient(ellipse at bottom, rgba(118, 75, 162, 0.15) 0%, transparent 50%);
	animation: gradientMove 8s ease-in-out infinite;
}

@keyframes gradientMove {
	0%, 100% {
		transform: scale(1) rotate(0deg);
		opacity: 1;
	}
	50% {
		transform: scale(1.1) rotate(5deg);
		opacity: 0.8;
	}
}

.particle {
	position: absolute;
	background: radial-gradient(circle, rgba(255, 255, 255, 0.8) 0%, rgba(255, 255, 255, 0) 70%);
	border-radius: 50%;
	opacity: 0.6;
	animation: float 4s ease-in-out infinite;
}

@keyframes float {
	0%, 100% {
		transform: translateY(0) translateX(0) scale(1);
		opacity: 0.4;
	}
	50% {
		transform: translateY(-30px) translateX(15px) scale(1.3);
		opacity: 0.8;
	}
}

// 返回按钮
.back-btn {
	position: absolute;
	top: 60rpx;
	left: 30rpx;
	width: 80rpx;
	height: 80rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background: rgba(255, 255, 255, 0.1);
	border-radius: 50%;
	z-index: 10;
	backdrop-filter: blur(10px);
}

// 主要内容
.content {
	position: relative;
	z-index: 1;
	height: 100%;
	display: flex;
	flex-direction: column;
	justify-content: center;
	padding: 0 60rpx;
}

// Logo区域
.logo-section {
	text-align: center;
	margin-bottom: 100rpx;
}

.logo {
	width: 120rpx;
	height: 120rpx;
	border-radius: 24rpx;
	margin-bottom: 20rpx;
}

.app-name {
	display: block;
	font-size: 48rpx;
	font-weight: bold;
	color: #fff;
	letter-spacing: 4rpx;
}

// 表单区域
.form-section {
	background: rgba(255, 255, 255, 0.05);
	border-radius: 24rpx;
	padding: 60rpx 40rpx;
	backdrop-filter: blur(10px);
	border: 1rpx solid rgba(255, 255, 255, 0.1);
}

// 切换标签
.tabs {
	display: flex;
	margin-bottom: 60rpx;
	border-bottom: 2rpx solid rgba(255, 255, 255, 0.1);
}

.tab {
	flex: 1;
	text-align: center;
	padding: 20rpx 0;
	font-size: 32rpx;
	color: #666;
	position: relative;
	transition: color 0.3s;
}

.tab.active {
	color: #fff;
	font-weight: 600;
}

.tab.active::after {
	content: '';
	position: absolute;
	bottom: -2rpx;
	left: 50%;
	transform: translateX(-50%);
	width: 60rpx;
	height: 4rpx;
	background: linear-gradient(90deg, #ff6b6b, #ffd93d);
	border-radius: 2rpx;
}

// 表单
.form {
	display: flex;
	flex-direction: column;
	gap: 40rpx;
}

.input-wrapper {
	display: flex;
	flex-direction: column;
	gap: 8rpx;
}

.input-group {
	display: flex;
	align-items: center;
	gap: 20rpx;
	padding: 24rpx 30rpx;
	background: rgba(255, 255, 255, 0.05);
	border-radius: 16rpx;
	border: 1rpx solid rgba(255, 255, 255, 0.1);
	transition: all 0.3s;
}

.input-group:focus-within {
	border-color: rgba(255, 255, 255, 0.3);
	background: rgba(255, 255, 255, 0.08);
}

.input-group.error {
	border-color: #ff6b6b;
	background: rgba(255, 107, 107, 0.1);
}

.error-message {
	padding: 0 30rpx;
	font-size: 24rpx;
	color: #ff6b6b;
	line-height: 1.5;
	display: flex;
	flex-direction: column;
	gap: 4rpx;
}

.input {
	flex: 1;
	font-size: 28rpx;
	color: #fff;
	background: transparent;
	border: none;
	outline: none;
}

.eye-icon {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 8rpx;
	cursor: pointer;
	transition: opacity 0.3s;
}

.eye-icon:active {
	opacity: 0.6;
}

.remember-me {
	display: flex;
	align-items: center;
	margin-top: -20rpx;
	margin-bottom: -20rpx;
}

.checkbox-wrapper {
	display: flex;
	align-items: center;
	gap: 12rpx;
	cursor: pointer;
}

.checkbox {
	width: 32rpx;
	height: 32rpx;
	border: 2rpx solid rgba(255, 255, 255, 0.3);
	border-radius: 6rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background: rgba(255, 255, 255, 0.05);
	transition: all 0.3s;
}

.checkbox.checked {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	border-color: #667eea;
}

.check-icon {
	font-size: 20rpx;
	color: #fff;
	font-weight: bold;
	line-height: 1;
}

.checkbox-label {
	font-size: 26rpx;
	color: rgba(255, 255, 255, 0.7);
	user-select: none;
}

.submit-btn {
	width: 100%;
	height: 88rpx;
	line-height: 88rpx;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	color: #fff;
	font-size: 32rpx;
	font-weight: 600;
	border-radius: 16rpx;
	border: none;
	margin-top: 20rpx;
	box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.4);
	transition: all 0.3s;
}

.submit-btn:active {
	transform: scale(0.98);
	box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
}
</style>
